import os
import json
import datetime
import pandas as pd
import landsatxplore.api
import configparser
from landsatxplore.earthexplorer import EarthExplorer


def request_landsat(username, password, product, bbox, start_date, end_date, cloud_max,max_results):
    api = landsatxplore.api.API(username, password)
    scenes = api.search(
        dataset=product,
        bbox=bbox,
        start_date=start_date,
        end_date=end_date,
        max_cloud_cover=cloud_max,
        max_results=max_results)
    print('{} scenes found.'.format(len(scenes)))
    api.logout()
    return scenes


def download_landsat(username, password, Landsat_name, output_dir, progress_dir):
    earth_down = EarthExplorer(username, password)
    for scene in Landsat_name:
        ID = scene['entityId']
        print('Downloading data :{} '.format(ID))
        out_id = [{"ID": ID}]
        data = pd.DataFrame(out_id)
        current_id_path = progress_dir + "/{}.csv".format("down_load_id")
        if not os.path.exists(current_id_path):
            earth_down.download(scene_id=ID, output_dir=output_dir)
            data.to_csv(current_id_path)
        else:
            df = pd.read_csv(current_id_path, index_col=0)
            download_data = df['ID'].tolist()
            if ID in download_data:
                print("Current {} file exists, skipping".format(ID))
            else:
                earth_down.download(scene_id=ID, output_dir=output_dir)
                df = df.append(data, ignore_index=True)
                df.to_csv(current_id_path)
    earth_down.logout()


if __name__ == '__main__':
    product = 'LANDSAT_8_C1'
    max_results = 500
    cloud_max = 0
    bbox = [-90, -180, 90, 180]
    conf = configparser.ConfigParser()
    conf.read(os.getcwd() + '/config/config.ini', encoding="utf-8")
    start_day = conf.get('LANDSAT', 'start_day')
    end_day = conf.get('LANDSAT', 'end_day')
    out_path = conf.get('LANDSAT', 'out_path')
    username = conf.get('LANDSAT', 'username')
    password = conf.get('LANDSAT', 'password')
    current_time = datetime.datetime.now().strftime('%Y%m%d')
    progress_dir = os.path.join(os.getcwd(), 'storage/progress')
    times_range = pd.date_range(start_day, end_day, freq='1D')
    for i in range(len(times_range)):
        str_time_current = times_range[i].strftime('%Y%m%d')
        str_time_net = times_range[i+1].strftime('%Y%m%d')
        year_str_c = str_time_current[0:4]
        month_str_c = str_time_current[4:6]
        day_str_c = str_time_current[6:8]
        year_str_n = str_time_current[0:4]
        month_str_n = str_time_current[4:6]
        day_str_n = str_time_current[6:8]
        start_one_day = year_str_c + '-' + month_str_c + '-' + day_str_c
        end_one_day = year_str_n + '-' + month_str_n + '-' + day_str_n
        print("Current download time is: {}".format(start_one_day))
        if not os.path.exists(progress_dir):
            os.makedirs(progress_dir)
        progress_name = progress_dir + '/progress_real_time_{}.json'.format('LANDSAT')
        if not os.path.exists(progress_name):
            with open(progress_name, 'w') as of:
                json.dump(str_time_current, of)
        with open(progress_name, 'r') as of:
            progress_time = json.load(of)
        if int(str_time_current) >= int(progress_time):
            Landsat_name = request_landsat(username, password, product, bbox, start_one_day, end_one_day, cloud_max, max_results)
            download_landsat(username, password, Landsat_name, out_path, progress_dir)
